from duetopia.metadata.base import *

class FGDC(Metadata):
    def extract(xml=None,file=None):
        if file is not None:
            try:
                xml = open(file).read()
            except:
                return

        i = etree.fromstring(xml)
        d = i.find('idinfo')
        dataset = Dataset()
            # abstract dataset properties - good to have a UUID if poss
        dataset.title = d.find('citation/citeinfo/title').text
        dataset.abstract = d.find('descript/abstract').text
        keywords = []
        for k in d.findall('keywords/theme/themekey'):
            keywords.append(k.text)
        dataset.keywords = keywords 
        bbox = d.find('spdom/bounding')
        if bbox is not None:
            # get extents
            extents = {} 
            # e.g. ext = [0.2,51.2,0.3,51.4]
            extents.east = bbox.find('eastbc').text
            extents.south = bbox.find('southbc').text
            extents.west = bbox.find('westbc').text
            extents.north = bbox.find('northbc').text
            # look for projection info
            # we should optionally transform to wgs84 here
            self.extents = extents
            # @@TODO - provide reference system information
            # d.projection = i.find('refSysInfo/RefSystem/refSysID/identCode').tex
            # specific datasources 
        datasource = Datasource()

        timespan = Timespan()
        temp = d.find('timeperd/timeinfo/rngdates')
        timespan.dtstart = temp.find('begdate').text
        timespan.dtend = temp.find('enddate').text

        # @@ agents related to dataset how?
        agent = Agent()
        info = d.find('citation/rrpInfo/cntinfo')
        agent.name = info.find('cntperp/cntper').text
        set(agent,'email',info.find('cntemail'))
        set(agent,'phone',info.find('cntvoice'))
        
        self.metadata = (dataset,datasource,agent,timespan)
       
    def export(self,file=file):
        pass 
